'''
Created on 2010-6-25

@author: Zizon
'''
from time import time
from com.google.code.zkit.twitter.oauth.Oauth import Oauth, quote
from com.google.code.zkit.twitter.oauth.Config import OauthConfig
import random

class OauthHeaderBuilder():
    
    @classmethod
    def buildHeaderByVaryParameter(self, url, method, token_secret, **extract_oauth_parameters):
        return OauthHeaderBuilder.buildHeaderByDict(url, method, token_secret, extract_oauth_parameters)
        
    @classmethod
    def buildHeaderByDict(self, url, method, token_secret, paramters):
        to_sign = {
                      "oauth_consumer_key":OauthConfig.oauth_consumer_key,
                      "oauth_nonce":str(random.getrandbits(32)),
                      "oauth_signature_method":OauthConfig.oauth_signature_method,
                      "oauth_timestamp":str(long(time())),
                      "oauth_version":OauthConfig.oauth_version,
                 }
        to_sign.update(paramters)
        to_sign["oauth_signature"] = Oauth.signingRequest(
                                        method,
                                        url,
                                        to_sign,
                                        OauthConfig.comsumer_secret,
                                        token_secret)
        to_sign = OauthHeaderBuilder.filtNoneOauthPart(to_sign)
        return {"Authorization":"OAuth %s" % (", ".join("%s=\"%s\"" % (quote(key), quote(value)) for key, value in to_sign.items()))}

    @classmethod
    def filtNoneOauthPart(self, source):
        for key in source.keys():
            if "oauth" not in key.lower() :
                source.pop(key)
        return source
